package com.adlotto2.lcdns.common;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

import com.adlotto2.lcdns.R;
import com.adlotto2.lcdns.cronos.asynctask.CNDataAsyncTask;

public abstract class BaseActivity extends Activity
implements CNDataAsyncTask.CNDataAsyncTaskCallback, DialogInterface.OnCancelListener
{
	protected abstract int onGetContentViewResource();

	protected abstract void onInit();

	private ProgressDialog mLoadingDialog = null;
	private CNDataAsyncTask mDataAsyncTask = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(onGetContentViewResource());

		onInit();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		System.gc();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		System.gc();
		cancelRequestData();
	}

	protected void cancelRequestData() {
		hideLoadingDialog();

		if (this.mDataAsyncTask != null && !this.mDataAsyncTask.isCancelled()) {
			this.mDataAsyncTask.cancel(true);
		}

		this.mDataAsyncTask = null;
	}

	protected void onRequestData() {
		if (!this.isFinishing()) {
			this.mDataAsyncTask = new CNDataAsyncTask(this, this);
			this.mDataAsyncTask.execute();
		}
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		cancelRequestData();
	}

	protected void showLoadingDialog() {
		showLoadingDialog(R.string.commons_loading);
	}
	
	protected void showLoadingDialog(Context context) {
		showLoadingDialog(R.string.commons_loading, context);
	}

	protected void showLoadingDialog(int msgResId) {
		if (!this.isFinishing()) {
			if (this.mLoadingDialog == null) {
				this.mLoadingDialog = new ProgressDialog(this);
				this.mLoadingDialog.setMessage(getString(msgResId));
				this.mLoadingDialog.setOnCancelListener(this);
			}

			this.mLoadingDialog.show();
		}
	}
	
	protected void showLoadingDialog(int msgResId, Context context) {
		if (!this.isFinishing()) {
			if (this.mLoadingDialog == null) {
				this.mLoadingDialog = new ProgressDialog(context);
				this.mLoadingDialog.setMessage(getString(msgResId));
				this.mLoadingDialog.setOnCancelListener(this);
			}

			this.mLoadingDialog.show();
		}
	}

	protected void hideLoadingDialog() {
		if (this.mLoadingDialog != null) {
			this.mLoadingDialog.dismiss();
			this.mLoadingDialog = null;
		}
	}
}